import PerfectHTTP
import PerfectHTTPServer
import PerfectMySQL
// 注册您自己的路由和请求／响应句柄


let testHost = "111.231.109.254"
let testUser = "root"
let testPassword = "bittest123"
let testDB = "bitbear_news"


func fetchData(){
    let mysql = MySQL()
    guard mysql.connect(host: testHost, user: testUser, password: testPassword, db: testDB, port: 3306) else {
        return
    }
//    defer {
//        mysql.close()
//    }
    
    // 执行查询或者创建表格
    let sql = """
    SELECT * FROM user;
    """
    guard mysql.query(statement: sql) else {
        // 验证是否创建成功
        print(mysql.errorMessage())
        return
    }
    guard mysql.query(statement: sql) else {return}
    let res = mysql.storeResults()!
    res.forEachRow { (row) in
        print(row)
    }
}

var routes = Routes()
routes.add(method: .get, uri: "/") {
    request, response in
    fetchData()
    response.setHeader(.contentType, value: "text/html")
    response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
        .completed()
}
routes.add(method: .get, uri: "/Hello") { (rq, rp) in
    rp.setHeader(.allow, value: "text/html")
    rp.appendBody(string: "xxxxx").completed()
}

do {
    // 启动HTTP服务器
    try HTTPServer.launch(
        .server(name: "0.0.0.0", port: 8181, routes: routes))
} catch {
    fatalError("\(error)") // fatal error launching one of the servers
}
